//
//  TheHomeManager.m
//  JiuKuGospel
//
//  Created by jiukuyinyue on 15-8-11.
//  Copyright (c) 2015年 JiuKuForApp. All rights reserved.
//

#import "TheHomeManager.h"

#import "JKSongsMessStatus.h"
#import "NetworkTool+LCAVPlay.h"
#import "TheHomeManager+Additions.h"

#define FUYIN_SHENGJING_PATH @"AllShengJingFile"
#define FUYIN_SHENGJ_ALLONE_PATH @"AllOneShengJFile"
#define SHIGE_PATH @"ShiGeFile"
#define LINGXIU_PATH @"LingXiuFile"
#define ZHUFU_ID @"ZhufuID"
#define SELECT_SHENGJ @"SelectShengJ"
#define SEARCH_HISTORY @"SearchHistoyr"
#define GAO_LIANG @"ShengJGaoliang"
#define KEY_ARCHIVER @"keyArchiver"
#define SONGS_GECI_PATH @"GeciFile"

static TheHomeManager * manager = nil;

@interface TheHomeManager ()

@end

@implementation TheHomeManager


+ (TheHomeManager *)shareTheHomeManager
{
    if (!manager) {
        manager = [[TheHomeManager alloc] init];
        manager.selectShengjDic = [NSMutableDictionary dictionary];
        manager.zhufuArr = [NSMutableArray array];
        manager.shengjingAllDic = [NSMutableDictionary dictionary];
        manager.shengjingNumZDic = [NSMutableDictionary dictionary];
        manager.shigeDic = [NSMutableDictionary dictionary];
        manager.lingxiuDic = [NSMutableDictionary dictionary];
        manager.shengjPlayBool = -1;
        manager.dataJiuyueArr = [NSMutableArray array];
        manager.dataXinyeuArr = [NSMutableArray array];
        manager.dataShengJingSongsArr = [NSMutableArray array];
        manager.dataShengJingLrcDic = [NSMutableDictionary dictionary];
        manager.timeArr = [NSMutableArray array];
        manager.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 15, 100, 30)];
        manager.timeLabel.textColor = JK_RED_COLOR;
        NSString *backupDbPath = [[NSBundle mainBundle]
                                  pathForResource:@"shengjing"
                                  ofType:@"db"];
        manager.db=[FMDatabase databaseWithPath:backupDbPath];
        [manager getLocalShengjing];

        manager.daogaoTitleArr = [NSMutableArray array];
        manager.daogaoMessageArr = [NSMutableArray array];
        manager.searchDic = [NSMutableDictionary dictionary];
        manager.gaoLiangDic = [NSMutableDictionary dictionary];
        
        manager.selectID = @"";
        manager.paiHangArr = [NSMutableArray array];
        manager.shige400Arr = [NSMutableArray array];
        //诗歌歌词
        manager.playGeCiDic = [NSMutableDictionary dictionaryWithCapacity:1];
//        [manager getAllMusicAboutGeci];

    }
    return manager;
}

-(void)setBibleName:(NSString *)bibleName{
    [[NSUserDefaults standardUserDefaults] setObject:bibleName forKey:@"bibleName"];
}
-(NSString *)bibleName{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"bibleName"] == nil) {
        return @"";
    } else {
        return [[NSUserDefaults standardUserDefaults] objectForKey:@"bibleName"];
    }
}

-(NSInteger)historyCount{
    if ([[self bibleName] isEqualToString:@""]) {
        return 1;//如果为空就返回第一章;
    }
    return [self getBibleIDWithSelectTitle:[self bibleName]];
}


- (void)saveUserMessages
{
    [manager.shengjingAllDic writeToFile:[self filePath:FUYIN_SHENGJING_PATH] atomically:YES];
    [manager.shengjingNumZDic writeToFile:[self filePath:FUYIN_SHENGJ_ALLONE_PATH] atomically:YES];
    [manager.shigeDic writeToFile:[self filePath:SHIGE_PATH] atomically:YES];
    [manager.lingxiuDic writeToFile:[self filePath:LINGXIU_PATH] atomically:YES];
    [manager.zhufuArr writeToFile:[self filePath:ZHUFU_ID] atomically:YES];
    [manager.selectShengjDic writeToFile:[self filePath:SELECT_SHENGJ] atomically:YES];
    

    //圣经高亮
    [manager.gaoLiangDic writeToFile:[self filePath:GAO_LIANG] atomically:YES];

    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:manager.gengXinImageStr forKey:@"gengxinImage"];
    [userDefaults setObject:manager.genXinHuanCStr forKey:@"gengxinHuanC"];
    //圣经保存上次浏览位置
    [userDefaults setObject:[NSString stringWithFormat:@"%zd", manager.tempIndexPath.section] forKey:@"tempIndexS"];
    [userDefaults setObject:[NSString stringWithFormat:@"%zd", manager.tempIndexPath.row] forKey:@"tempIndexR"];
    [userDefaults setObject:[NSString stringWithFormat:@"%zd", manager.tempCount] forKey:@"tempIndexCount"];
    [userDefaults synchronize];

}

- (void)getUserMessages
{
    NSDictionary * dic = [NSDictionary dictionaryWithContentsOfFile:[self filePath:FUYIN_SHENGJING_PATH]];
    [manager.shengjingAllDic setDictionary:dic];
    NSDictionary * allOneDic = [NSDictionary dictionaryWithContentsOfFile:[self filePath:FUYIN_SHENGJ_ALLONE_PATH]];
    [manager.shengjingNumZDic setDictionary:allOneDic];
    NSDictionary * shigedic = [NSDictionary dictionaryWithContentsOfFile:[self filePath:SHIGE_PATH]];
    [manager.shigeDic setDictionary:shigedic];
    NSDictionary * lingxiuDic = [NSDictionary dictionaryWithContentsOfFile:[self filePath:LINGXIU_PATH]];
    [manager.lingxiuDic setDictionary:lingxiuDic];
    NSArray * zhufuIDArr = [NSArray arrayWithContentsOfFile:[self filePath:ZHUFU_ID]];
    [manager.zhufuArr addObjectsFromArray:zhufuIDArr];
    NSDictionary * selectShengJ = [NSDictionary dictionaryWithContentsOfFile:[self filePath:SELECT_SHENGJ]];
    [manager.selectShengjDic setDictionary:selectShengJ];
    
    //圣经高亮
    NSDictionary * ShengJGaoLiang = [NSDictionary dictionaryWithContentsOfFile:[self filePath:GAO_LIANG]];
    NSArray * allKeys = [ShengJGaoLiang allKeys];
    if (allKeys.count != 0) {
        for (NSString * key in allKeys) {
            NSArray * gaoliangArr = [ShengJGaoLiang objectForKey:key];
            NSMutableArray * tempArr = [NSMutableArray arrayWithArray:gaoliangArr];
            [self.gaoLiangDic setValue:tempArr forKey:key];
        }
    }
    

    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    manager.gengXinImageStr = [userDefaults objectForKey:@"gengxinImage"] ;
    manager.genXinHuanCStr = [userDefaults objectForKey:@"gengxinHuanC"] ;
    NSString * section = [userDefaults objectForKey:@"tempIndexS"];
    NSString * row = [userDefaults objectForKey:@"tempIndexR"];
    NSString * count = [userDefaults objectForKey:@"tempIndexCount"];
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[row integerValue] inSection:[section integerValue]];
    manager.tempIndexPath = indexPath;
    manager.tempCount = [count integerValue];
}

- (void)clearUserMessages
{
    [manager.shigeDic removeAllObjects];
}


//退出的歌曲沙盒存储路径
- (NSString *)filePath:(NSString *)path
{
    NSString * documents = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    NSString * filePath = [documents stringByAppendingPathComponent:path];
    return filePath;
}


//归档
- (void)archiverMessage
{
    NSMutableData * data = [NSMutableData data];
    NSKeyedArchiver * keyArchiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [keyArchiver encodeObject:self.paiHangArr forKey:@"paiHangArr"];
    [keyArchiver encodeObject:self.shige400Arr forKey:@"shige400Arr"];
    [keyArchiver finishEncoding];
    [data writeToFile:[self filePath:KEY_ARCHIVER] atomically:YES];
}

//解档
- (void)unArchiverMessage
{
    NSData * data = [NSData dataWithContentsOfFile:[self filePath:KEY_ARCHIVER]];
    NSKeyedUnarchiver * unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    
    NSArray * paiH = [unArchiver decodeObjectForKey:@"paiHangArr"];
    NSArray * shiG = [unArchiver decodeObjectForKey:@"shige400Arr"];
    
    [unArchiver finishDecoding];
    [self.paiHangArr addObjectsFromArray:paiH];
    [self.shige400Arr addObjectsFromArray:shiG];
    
    
    
}



//获取本地圣经
- (void)getLocalShengjing
{
    if (!_db)
    {
        NSLog(@"数据库创建不成功");
    }else{
        if([_db open])
        {
            NSLog(@"数据库创建成功并打开");
            
            NSString *sql = [NSString stringWithFormat:@"select * from Book"];
            FMResultSet *result = [_db executeQuery:sql];
            while ([result next])
            {
                NSString * uid=[result stringForColumn:@"parentId"];
                if ([uid isEqualToString:@"jiuyue"]) {
//                    NSLog(@"旧约信息");
                    NSMutableDictionary * tempDic = [NSMutableDictionary dictionary];
                    [tempDic setValue:[result stringForColumn:@"content"] forKey:@"name"];
                    [tempDic setValue:[result stringForColumn:@"title"] forKey:@"title"];
                    [tempDic setValue:[result stringForColumn:@"id"] forKey:@"id"];
                    [tempDic setObject:[result stringForColumn:@"count"] forKey:@"count"];
                    [manager.dataJiuyueArr addObject:tempDic];
                }else{
//                    NSLog(@"新约信息");
                    NSMutableDictionary * tempDic = [NSMutableDictionary dictionary];
                    [tempDic setValue:[result stringForColumn:@"content"] forKey:@"name"];
                    [tempDic setValue:[result stringForColumn:@"title"] forKey:@"title"];
                    [tempDic setValue:[result stringForColumn:@"id"] forKey:@"id"];
                    [tempDic setObject:[result stringForColumn:@"count"] forKey:@"count"];
                    [manager.dataXinyeuArr addObject:tempDic];
                }
            }
            [_db close];
        }
    }
}
//查询圣经信息
- (void)localShengJingSongMessage:(NSString *)selectID
{
    _selectID = selectID;
    if ([selectID integerValue] < 0) {
        selectID = @"66";
    }
    if ([selectID integerValue]> 66) {
        selectID = @"1";
    }
    [manager.dataShengJingSongsArr removeAllObjects];
    
    if (!_db)
    {
        NSLog(@"数据库创建不成功");
    }else{
        if([_db open])
        {
            NSLog(@"数据库创建成功并打开");
            
            
            //查询圣经信息
            NSString *sql2 = [NSString stringWithFormat:@"select * from Song"];
            FMResultSet *result2 = [_db executeQuery:sql2];
            while ([result2 next])
            {
                NSString * uid=[result2 stringForColumn:@"parentId"];
                if ([uid isEqualToString:selectID]) {
                    NSMutableDictionary * tempDic = [NSMutableDictionary dictionary];
                    [tempDic setValue:[result2 stringForColumn:@"singerName"] forKey:@"singerName"];
                    [tempDic setValue:[result2 stringForColumn:@"title"] forKey:@"title"];
                    [tempDic setValue:[result2 stringForColumn:@"musicId"] forKey:@"musicId"];
                    [tempDic setValue:[result2 stringForColumn:@"id"] forKey:@"id"];
                    [tempDic setObject:[result2 stringForColumn:@"fileUrl"] forKey:@"fileUrl"];
                    [tempDic setObject:[result2 stringForColumn:@"duration"] forKey:@"duration"];
                    [manager.dataShengJingSongsArr addObject:tempDic];
                }
            }
            [LSZSpecialPackaging addPlaylistWithArrayData:manager.dataShengJingSongsArr];  //让播放器获取圣经歌曲列表
            [_db close];
        }
    }

}
//查询圣经歌词
- (void)localShengJingLrc:(NSString *)selectID
{
    [manager.dataShengJingLrcDic removeAllObjects];
    [manager.timeArr removeAllObjects];
         if (!_db)
        {
            NSLog(@"数据库创建不成功");
        }else{
            if([_db open])
            {
                NSLog(@"数据库创建成功并打开");
                                
                //查询圣经歌词
                NSString *sql3 = [NSString stringWithFormat:@"select * from Lyric"];
                FMResultSet *result3 = [_db executeQuery:sql3];
                NSMutableString *mutableString = [[NSMutableString alloc] init];
                _mutableString = mutableString;
                while ([result3 next])
                {
                    NSString * uid=[result3 stringForColumn:@"parentId"];
                    if ([uid isEqualToString:selectID]) {
                        NSString * timeStr = [result3 stringForColumn:@"startTime"];
                        NSInteger durationTime = [timeStr integerValue];
                        NSInteger num1 = durationTime/60000;
                        NSInteger num2 = durationTime%60000/1000;
                        NSString * startTimeStr = nil;
                        if (num1<10) {
                            if (num2<10) {
                                startTimeStr = [NSString stringWithFormat:@"0%ld:0%ld", (long)num1, (long)num2];
                            }else
                               startTimeStr = [NSString stringWithFormat:@"0%ld:%ld", (long)num1, (long)num2];
                        }else{
                            if (num2<10) {
                                startTimeStr = [NSString stringWithFormat:@"%ld:0%ld", (long)num1, (long)num2];
                            }else
                                startTimeStr = [NSString stringWithFormat:@"%ld:%ld", (long)num1, (long)num2];
                        }

                        [_mutableString appendString:[NSString stringWithFormat:@"[%@]%@",startTimeStr,[result3 stringForColumn:@"content"]]];
                        [manager.dataShengJingLrcDic setValue:[result3 stringForColumn:@"content"] forKey:startTimeStr];
                        [manager.timeArr addObject:startTimeStr];

                    }
                }
                [_db close];
                //回到主线程取刷新UI
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    NSLog(@"回到主线程刷新UI");
                }];
            }
        }
}
//祷告词库 数据
- (NSArray *)localDaoGaoCikuTitle
{
    NSMutableArray * daogaoTitleArr = [NSMutableArray array];
        if (!_db)
        {
            NSLog(@"数据库创建不成功");
        }else{
            if([_db open])
            {
                NSLog(@"数据库创建成功并打开");
                                
                //查询圣经歌词
                NSString *sql3 = [NSString stringWithFormat:@"select * from PrayCatalog"];
                FMResultSet *result3 = [_db executeQuery:sql3];
                while ([result3 next])
                {
                    NSString * uid=[result3 stringForColumn:@"id"];
                    NSString * title = [result3 stringForColumn:@"title"];
                    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                    [dic setValue:uid forKey:@"id"];
                    [dic setValue:title forKey:@"name"];
                    [daogaoTitleArr addObject:dic];
                }
                [_db close];
                //回到主线程取刷新UI
            }
        }
    return daogaoTitleArr;
}
//祷告词库 数据
- (NSArray *)localDaoGaoCikuMessage:(NSString *)selectId
{
    NSMutableArray * daogaoMessageArr = [NSMutableArray array];
    if (!_db)
    {
        NSLog(@"数据库创建不成功");
    }else{
        if([_db open])
        {
            NSLog(@"数据库创建成功并打开");
            //查询圣经歌词
            NSString *sql3 = [NSString stringWithFormat:@"select * from PrayInfo"];
            FMResultSet *result3 = [_db executeQuery:sql3];
            while ([result3 next])
            {
                NSString * uid=[result3 stringForColumn:@"parentId"];
                if ([uid isEqualToString:selectId]) {
                    NSString * title = [result3 stringForColumn:@"title"];
                    NSString * content = [result3 stringForColumn:@"content"];
                    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                    [dic setValue:content forKey:@"str"];
                    [dic setValue:title forKey:@"title"];
                    [daogaoMessageArr addObject:dic];

                }
            }
            [_db close];
            //回到主线程取刷新UI
        }
    }
    return daogaoMessageArr;
}
- (void)reloadSearch
{
}
#pragma mark -诗歌歌词
//数据缓存存入沙盒
- (void)saveAllMusicAboutGeci
{
    [[TheHomeManager shareTheHomeManager].playGeCiDic writeToFile:[self filePath:SONGS_GECI_PATH] atomically:YES];;
}
//数据从沙盒中读取
- (void)getAllMusicAboutGeci
{
    NSDictionary * geciDic = [NSDictionary dictionaryWithContentsOfFile:[self filePath:SONGS_GECI_PATH]];
    [[TheHomeManager shareTheHomeManager].playGeCiDic setValuesForKeysWithDictionary:geciDic];
}
//搜索功能的需要
- (void)searchShengJingLrc:(NSString *)searchStr
{
    [manager.thread cancel];
    manager.searchStr = searchStr;
    NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(doThread) object:nil];
    manager.thread = thread;
    [thread start];
    
}
- (void)doThread {
    NSString * searchStr = manager.searchStr;
    NSMutableDictionary * tempDic = [NSMutableDictionary dictionary];
    if (!_db)
    {
        NSLog(@"数据库创建不成功");
    }else{
        if([_db open])
        {
            NSLog(@"数据库创建成功并打开");
            
            //查询圣经歌词
            NSString *sql3 = [NSString stringWithFormat:@"select * from Lyric"];
            FMResultSet *result3 = [_db executeQuery:sql3];
            while ([result3 next])
            {
                if (manager.searchBool) {
                    [_db close];
                    manager.searchBool = NO;
                    return;
                }
                NSString * lrcCount = [result3 stringForColumn:@"content"];
                if ([lrcCount rangeOfString:searchStr].location != NSNotFound) {
                    if ([result3 stringForColumn:@"parentId"].length != 0) {
                        [tempDic setValue:lrcCount forKey:[result3 stringForColumn:@"parentId"]];
                    }
                }
            }
            //查询圣经信息
            NSString *sql2 = [NSString stringWithFormat:@"select * from Song"];
            FMResultSet *result2 = [_db executeQuery:sql2];
            while ([result2 next])
            {
                NSInteger parentId = [[result2 stringForColumn:@"parentId"] integerValue];
                
                if (parentId < 40) {
                    NSString * uid=[result2 stringForColumn:@"id"];
                    if ([[tempDic allKeys] containsObject:uid]) {
                        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                        [dic setValue:[tempDic objectForKey:uid] forKey:@"content"];
                        [dic setValue:[result2 stringForColumn:@"title"] forKey:@"title"];
                        [dic setValue:[result2 stringForColumn:@"parentId"] forKey:@"parentId"];
                    }
                    //旧约数据
                }
                if (parentId >40) {
                    //新约数据
                    NSString * uid=[result2 stringForColumn:@"id"];
                    if ([[tempDic allKeys] containsObject:uid]) {
                        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
                        [dic setValue:[tempDic objectForKey:uid] forKey:@"content"];
                        [dic setValue:[result2 stringForColumn:@"title"] forKey:@"title"];
                        [dic setValue:[result2 stringForColumn:@"parentId"] forKey:@"parentId"];
                    }
                }
                
            }
            [_db close];
            //回到主线程取刷新UI
            [self performSelectorOnMainThread:@selector(reloadSearch) withObject:nil waitUntilDone:YES];
            
        }
    }
    
}

///初始化值
-(NSMutableArray *)dataJiuyueArr{
    if (_dataJiuyueArr == nil) {
        [self getLocalShengjing];
    }
    return _dataJiuyueArr;
}
-(NSIndexPath *)tempIndexPath{
    if (_tempIndexPath == nil) {
        NSIndexPath *createIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        _tempIndexPath = createIndexPath;
    }
    return _tempIndexPath;
}
@end
